package com.sagereal.wtc.factorymode.Activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.util.Locale;

public class BaseActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        applySavedLanguage();
    }

    protected void switchLanguage(String lang, String country) {
        // 保存当前语言设置
        saveLanguageSetting(lang, country);
        // 设置新的语言环境
        setLocale(lang, country);
        // 重新创建活动以应用新语言
        recreate();
    }

    protected void applySavedLanguage() {
        SharedPreferences prefs = getSharedPreferences("settings", Context.MODE_PRIVATE);
        String lang = prefs.getString("language", "zh");
        String country = prefs.getString("country", "CN");
        setLocale(lang, country);
    }

    private void saveLanguageSetting(String lang, String country) {
        SharedPreferences prefs = getSharedPreferences("settings", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("language", lang);
        editor.putString("country", country);
        editor.apply();
    }

    protected void setLocale(String lang, String country) {
        Locale locale = new Locale(lang, country);
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.setLocale(locale);//locale = locale;
        getResources().updateConfiguration(config, getResources().getDisplayMetrics());
    }

    @Override
    protected void onResume() {
        super.onResume();
        applySavedLanguage();
    }
}
